package com.siping.leetcode.剑指offer.day01;

/**
 * @author Yang Xu
 * @date 2021/8/17 8:53
 * @description: 剑指 Offer 30. 包含min函数的栈
 * https://leetcode-cn.com/problems/bao-han-minhan-shu-de-zhan-lcof/
 */
public class MinStack {
    private Node headNode;

    public MinStack() {

    }

    public void push(int x) {
        if (headNode == null) {
            headNode = new Node(x, x);
        } else {
            headNode = new Node(x, Math.min(x, headNode.min), headNode);
        }
    }

    public void pop() {
        headNode = headNode.next;
    }

    public int top() {
        return headNode.val;
    }

    public int min() {
        return headNode.min;
    }

    private class Node {
        private int val;
        private int min;
        private Node next;

        public Node(int val, int min) {
            this.val = val;
            this.min = min;
        }

        public Node(int val, int min, Node next) {
            this.val = val;
            this.min = min;
            this.next = next;
        }
    }

    public static void main(String[] args) {
        MinStack minStack = new MinStack();
        minStack.push(-10);
        minStack.push(14);
        System.out.println(minStack.min());
        System.out.println(minStack.min());
        minStack.push(-20);
        System.out.println(minStack.min());
        System.out.println(minStack.min());
        System.out.println(minStack.top());
        System.out.println(minStack.min());
        minStack.pop();

        minStack.push(10);
        minStack.push(-7);
        System.out.println(minStack.min());
        minStack.push(-7);
        minStack.pop();

        System.out.println(minStack.top());
        System.out.println(minStack.min());
        minStack.pop();

    }
}
